<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="page-title">{{ isEdit ? '编辑轮回' : '新增轮回' }}</h1>
        <div class="breadcrumb-container">
          <router-link to="/" class="link link-hover">首页</router-link>
          <span class="mx-2">/</span>
          <router-link to="/reincarnation" class="link link-hover">轮回管理</router-link>
          <span class="mx-2">/</span>
          <span>{{ isEdit ? '编辑轮回' : '新增轮回' }}</span>
        </div>
      </div>
      <div class="btn-group">
        <button class="btn btn-ghost" @click="handleCancel">取消</button>
        <button
          class="btn btn-primary"
          :class="{ loading: isSubmitting }"
          @click="handleSubmit"
        >
          保存
        </button>
      </div>
    </div>

    <!-- 表单 -->
    <div class="card bg-base-100 shadow-lg">
      <div class="card-body">
        <form @submit.prevent="handleSubmit" class="space-y-6">
          <!-- 魂魄选择 -->
          <div v-if="!isEdit">
            <h2 class="card-title">魂魄选择</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mt-4">
              <div class="form-control">
                <label class="label">
                  <span class="label-text">魂魄</span>
                </label>
                <select
                  v-model="form.soulId"
                  class="select select-bordered"
                  :class="{ 'select-error': errors.soulId }"
                >
                  <option value="">请选择魂魄</option>
                  <option v-for="soul in souls" :key="soul.id" :value="soul.id">
                    {{ soul.name }}
                  </option>
                </select>
                <label class="label" v-if="errors.soulId">
                  <span class="label-text-alt text-error">{{ errors.soulId }}</span>
                </label>
              </div>
            </div>
          </div>

          <!-- 轮回信息 -->
          <div>
            <h2 class="card-title">轮回信息</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mt-4">
              <div class="form-control">
                <label class="label">
                  <span class="label-text">投胎地点</span>
                </label>
                <input
                  v-model="form.location"
                  type="text"
                  placeholder="请输入投胎地点"
                  class="input input-bordered"
                  :class="{ 'input-error': errors.location }"
                />
                <label class="label" v-if="errors.location">
                  <span class="label-text-alt text-error">{{ errors.location }}</span>
                </label>
              </div>
              <div class="form-control">
                <label class="label">
                  <span class="label-text">新身份</span>
                </label>
                <input
                  v-model="form.newIdentity"
                  type="text"
                  placeholder="请输入新身份"
                  class="input input-bordered"
                  :class="{ 'input-error': errors.newIdentity }"
                />
                <label class="label" v-if="errors.newIdentity">
                  <span class="label-text-alt text-error">{{ errors.newIdentity }}</span>
                </label>
              </div>
              <div class="form-control" v-if="isEdit">
                <label class="label">
                  <span class="label-text">状态</span>
                </label>
                <select
                  v-model="form.status"
                  class="select select-bordered"
                  :class="{ 'select-error': errors.status }"
                >
                  <option value="pending">待执行</option>
                  <option value="processing">执行中</option>
                  <option value="completed">已完成</option>
                </select>
                <label class="label" v-if="errors.status">
                  <span class="label-text-alt text-error">{{ errors.status }}</span>
                </label>
              </div>
            </div>
          </div>

          <!-- 轮回详情 -->
          <div>
            <h2 class="card-title">轮回详情</h2>
            <div class="space-y-4 mt-4">
              <div class="form-control">
                <label class="label">
                  <span class="label-text">轮回原因</span>
                </label>
                <textarea
                  v-model="form.reason"
                  class="textarea textarea-bordered"
                  rows="4"
                  placeholder="请输入轮回原因"
                  :class="{ 'textarea-error': errors.reason }"
                ></textarea>
                <label class="label" v-if="errors.reason">
                  <span class="label-text-alt text-error">{{ errors.reason }}</span>
                </label>
              </div>
              <div class="form-control">
                <label class="label">
                  <span class="label-text">新世条件</span>
                </label>
                <textarea
                  v-model="form.conditions"
                  class="textarea textarea-bordered"
                  rows="4"
                  placeholder="请输入新世条件"
                  :class="{ 'textarea-error': errors.conditions }"
                ></textarea>
                <label class="label" v-if="errors.conditions">
                  <span class="label-text-alt text-error">{{ errors.conditions }}</span>
                </label>
              </div>
              <div class="form-control">
                <label class="label">
                  <span class="label-text">备注</span>
                </label>
                <textarea
                  v-model="form.remarks"
                  class="textarea textarea-bordered"
                  rows="2"
                  placeholder="请输入备注"
                ></textarea>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ReincarnationService, SoulService } from '@/api/services'
import { useLoadingStore } from '@/stores/loading'
import { useToast } from '@/composables/useToast'

const route = useRoute()
const router = useRouter()
const loadingStore = useLoadingStore()
const toast = useToast()

const id = route.params.id as string
const isEdit = computed(() => !!id)
const isSubmitting = ref(false)

// 表单
interface Form {
  soulId: string
  location: string
  newIdentity: string
  reason: string
  conditions: string
  remarks: string
  status?: 'pending' | 'processing' | 'completed'
}

interface FormErrors {
  soulId?: string
  location?: string
  newIdentity?: string
  reason?: string
  conditions?: string
  status?: string
}

const form = reactive<Form>({
  soulId: '',
  location: '',
  newIdentity: '',
  reason: '',
  conditions: '',
  remarks: '',
  status: undefined,
})

const errors = reactive<FormErrors>({})

// 魂魄列表
const souls = ref([])

// 方法
const validateForm = () => {
  let isValid = true
  errors.soulId = ''
  errors.location = ''
  errors.newIdentity = ''
  errors.reason = ''
  errors.conditions = ''
  errors.status = ''

  if (!isEdit.value && !form.soulId) {
    errors.soulId = '请选择魂魄'
    isValid = false
  }

  if (!form.location) {
    errors.location = '请输入投胎地点'
    isValid = false
  }

  if (!form.newIdentity) {
    errors.newIdentity = '请输入新身份'
    isValid = false
  }

  if (!form.reason) {
    errors.reason = '请输入轮回原因'
    isValid = false
  }

  if (!form.conditions) {
    errors.conditions = '请输入新世条件'
    isValid = false
  }

  if (isEdit.value && !form.status) {
    errors.status = '请选择状态'
    isValid = false
  }

  return isValid
}

const handleSubmit = async () => {
  if (!validateForm()) return

  try {
    isSubmitting.value = true
    loadingStore.show()

    if (isEdit.value) {
      const { soulId, ...updateParams } = form
      await ReincarnationService.updateReincarnation(id, updateParams)
      toast.success('修改成功')
    } else {
      await ReincarnationService.createReincarnation(form)
      toast.success('创建成功')
    }

    router.push('/reincarnation')
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    isSubmitting.value = false
    loadingStore.hide()
  }
}

const handleCancel = () => {
  router.back()
}

const loadReincarnation = async () => {
  if (!isEdit.value) return

  try {
    loadingStore.show()
    const data = await ReincarnationService.getReincarnation(id)
    form.soulId = data.soul.id
    form.location = data.location
    form.newIdentity = data.newIdentity
    form.reason = data.reason
    form.conditions = data.conditions
    form.remarks = data.remarks
    form.status = data.status
  } catch (error: any) {
    toast.error(error.message)
    router.push('/reincarnation')
  } finally {
    loadingStore.hide()
  }
}

const loadSouls = async () => {
  if (isEdit.value) return

  try {
    loadingStore.show()
    const { items } = await SoulService.getSouls({
      status: 'judged',
      page: 1,
      pageSize: 100,
    })
    souls.value = items
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    loadingStore.hide()
  }
}

// 生命周期
onMounted(() => {
  loadReincarnation()
  loadSouls()
})
</script>

<style scoped>
.badge {
  @apply px-2 py-1;
}
</style>
